<?php

declare(strict_types=1);

namespace App\Common\Service;
use afs\Request\V20180112 as Afs;
use AlibabaCloud\SDK\Captcha\V20230305\Captcha;
use AlibabaCloud\SDK\Captcha\V20230305\Models\VerifyIntelligentCaptchaRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use App\Setting\Service\SettingConfigService;
use Darabonba\OpenApi\Models\Config;

class AliyunService
{

    /**
     * 阿里云滑动验证码
     * @param $param
     * @return bool
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function slide($param): bool
    {
        $isTest = env('IS_LOCAL',false);
        if($isTest){
            //本地跳过验证
            return true;
        }

        if(empty($param['sessionId']) || empty($param['slideToken']) || empty($param['sig']) || empty($param['scene'])){
            return false;
        }
        //验证码配置管理appkey
        $config = container()->get(SettingConfigService::class);
        $appKey      = $config->getConfigByKey('slide_nc_login')['value'] ?? '';
        $AccessKeyID = $config->getConfigByKey('AccessKeyID')['value'] ?? '';
        $AccessKeySecret = $config->getConfigByKey('AccessKeySecret')['value'] ?? '';
        $setRemoteIp = get_client_ip();

        //YOUR ACCESS_KEY、YOUR ACCESS_SECRET请替换成您的阿里云accesskey id和secret
        $iClientProfile = \DefaultProfile::getProfile("cn-hangzhou", $AccessKeyID, $AccessKeySecret);
        $client = new \DefaultAcsClient($iClientProfile);
        \DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", "afs", "afs.aliyuncs.com");

        $request = new Afs\AuthenticateSigRequest();
        $request->setSessionId($param['sessionId']);  // 必填参数，从前端获取，不可更改，android和ios只传这个参数即可
        $request->setToken($param['slideToken']);          // 必填参数，从前端获取，不可更改
        $request->setSig($param['sig']);              // 必填参数，从前端获取，不可更改
        $request->setScene($param['scene']);          // 必填参数，从前端获取，不可更改
        $request->setAppKey($appKey);                 // 必填参数，后端填写
        $request->setRemoteIp($setRemoteIp);          // 必填参数，后端填写

        $response = $client->getAcsResponse($request);//返回code 100表示验签通过，900表示验签失败
        //返回code 100表示验签通过，900表示验签失败
        if ($response->Code == 100) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 阿里云滑块验证2.0版本
     * @param $args
     * @return bool
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function newSlide($args)
    {
        $config = new Config([
            "accessKeyId" => 'LTAI5t5mc8W7tbfiNAfpPN4A',
            "accessKeySecret" => 'yJqaK8zTbFvnbKseCT3ofPNnoqk9mZ'
        ]);
        $config->endpoint = "captcha.cn-shanghai.aliyuncs.com";
        $client =  new Captcha($config);
        $verifyIntelligentCaptchaRequest = new VerifyIntelligentCaptchaRequest();
        $verifyIntelligentCaptchaRequest->captchaVerifyParam = $args;
        $verifyIntelligentCaptchaRequest->sceneId = '2kb9hr8w';
        $runtime = new RuntimeOptions([]);
        try {
            $response = $client->verifyIntelligentCaptchaWithOptions($verifyIntelligentCaptchaRequest, $runtime);
            $verifyResult = $response->body->result->verifyResult;
            return $verifyResult;
        }
        catch (\Throwable $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            logger()->info('滑块验证失败'.$error->message);
            return false;
        }
    }
}